<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\db\Exception;

/**
 * LoginForm is the model behind the login form.
 *
 * @property User|null $user This property is read-only.
 *
 */
class LoginForm extends Model
{
    public $username;
    public $password;
    public $rememberMe = true;

    private $_user = false;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['username', 'password'], 'required'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
            // 添加密码强度验证规则，例如密码长度至少为8位
            ['password','string','min' => 6, 'tooShort' => '密码长度至少为6位'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            try {
                $user = $this->getUser();
                if (!$user ||!$user->validatePassword($this->password, $user->password_hash)) {
                    $this->addError($attribute, 'Incorrect username or password.');
                }
            } catch (Exception $e) {
                Yii::error('获取用户信息时出现数据库错误: '. $e->getMessage(), __METHOD__);
                $this->addError($attribute, '获取用户信息时出现错误，请稍后再试');
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     * @param \yii\web\User $userComponent Yii的user组件实例，用于执行登录操作
     * @return bool whether the user is logged in successfully
     */
    public function login($userComponent = null)
    {
        if ($this->validate()) {
            $user = $this->getUser();
            if ($user) {
                $userComponent = $userComponent?: Yii::$app->user;
                return $userComponent->login($user, $this->rememberMe? 3600*24*30 : 0);
            }
        }
        return false;
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    public function getUser()
    {
        if ($this->_user === false) {
            try {
                $this->_user = User::findByUsername($this->username);
            } catch (Exception $e) {
                Yii::error('查询用户信息时出现数据库错误: '. $e->getMessage(), __METHOD__);
                $this->_user = null;
            }
        }

        return $this->_user;
    }
}